package com.example.springbootmybatispage.handler;

import com.example.springbootmybatispage.model.SexEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 自定义类型处理器
 */
//@MappedTypes({SexEnum.class})
public class SexEnumTypeHandler extends BaseTypeHandler<SexEnum> {

    private Class<SexEnum> type;

    public SexEnumTypeHandler() {
    }

    public SexEnumTypeHandler(Class<SexEnum> type) {
        if (type == null) throw new IllegalArgumentException("Type argument cannot be null");
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, SexEnum parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getValue());
    }

    @Override
    public SexEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return convert(rs.getInt(columnName));
    }

    @Override
    public SexEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return convert(rs.getInt(columnIndex));
    }

    @Override
    public SexEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return convert(cs.getInt(columnIndex));
    }

    /**
     * 查询出来的字段值
     * @param value 查询出来的字段值
     * @return
     */
    private SexEnum convert(int value) {
        SexEnum[] objs = type.getEnumConstants();
        for (SexEnum em : objs) {
            if (em.getValue() == value) {
                return em;
            }
        }
        return null;
    }
}
